package cn.globalph.housekeeper.ui.main

import android.Manifest
import android.app.Activity
import android.app.AlarmManager
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.PowerManager
import android.provider.Settings
import android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.findNavController
import cn.globalph.housekeeper.BuildConfig
import cn.globalph.housekeeper.R
import cn.globalph.housekeeper.data.retrofit.HttpManager
import cn.globalph.housekeeper.data.source.PreferenceManager
import cn.globalph.housekeeper.databinding.ActivityMainBinding
import cn.globalph.housekeeper.service.UpdateService
import cn.globalph.housekeeper.ui.BaseActivity
import cn.globalph.housekeeper.ui.dialog.AlertDialogFragment
import cn.globalph.housekeeper.ui.dialog.DownLoaderDialog
import cn.globalph.housekeeper.ui.dialog.UpdateAppDialog
import cn.globalph.housekeeper.utils.AlarmUtil
import cn.globalph.housekeeper.utils.GPSUtil
import cn.globalph.housekeeper.utils.SystemUtils
import cn.globalph.housekeeper.utils.lifecycle.LocationObserver
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions
import java.lang.Exception
import java.util.*

const val STORAGE_PERMISSION = 24
const val REQUEST_IGNORE_BATTERY_CODE = 1001
class MainActivity : BaseActivity(), EasyPermissions.PermissionCallbacks {

    companion object{
        var handler = Handler()
    }

    private var updateUrl:String? = null
    private val updatePermission = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    private lateinit var locationObserver: LocationObserver

    private lateinit var binding: ActivityMainBinding
    @Suppress("UNCHECKED_CAST")
    private val viewModel by lazy {
        ViewModelProviders.of(this, object : ViewModelProvider.Factory {
            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                val repository = MainRepository(HttpManager.getInstance())
                return MainViewModel(repository) as T
            }
        }).get(MainViewModel::class.java)
    }

    override fun initView() {

        Log.i("MainActivity","oncreate")
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.viewModel = viewModel
        binding.lifecycleOwner = this


        locationObserver = LocationObserver(this@MainActivity)
        locationObserver.locationListener = object :LocationObserver.LocationListener{
            override fun onReceiveLocation(lat: Double, lon: Double) {
                viewModel.uploadLocation(lat.toString(),lon.toString())
            }

            override fun onPermissionDeney() {
//                Log.i("perdeny","perdeny")
                finish()
            }
        }
        val runnable = object : Runnable{
            override fun run() {
                locationObserver.start()
                val calendar = Calendar.getInstance()
                val time = calendar.get(Calendar.HOUR_OF_DAY)
                if(BuildConfig.DEBUG || (time in 7..18)){
                    handler.postDelayed(this,UPLOAD_DELAY)
                }
            }
        }
        handler.removeMessages(0)
        handler.postDelayed(runnable,500)

        Log.i("MANUFACTURER",android.os.Build.MANUFACTURER)

        reStartAlarm()
        viewModel.start(SystemUtils.getVersionCode(this), 1)

        viewModel.showUpdateDialog.observe(this, Observer {
            if (it) {
                val updateDialog = UpdateAppDialog()
                val bundle = Bundle()
                bundle.putParcelable("update", viewModel.updateModel.value)
                updateDialog.arguments = bundle
                updateDialog.setListener(object : UpdateAppDialog.VisitorListener {
                    override fun onClickUpload() {
                        updateUrl = viewModel.updateModel.value!!.appurl
                        downLoadUpdate()
//                        refreshUserProfile()
                    }

                    override fun onClickClose() {
//                        refreshUserProfile()
                    }

                    override fun onSkip() {
//                        PreferenceManager.ignoreVersionCode(getContext(), update.getVersioncode())
                    }
                }).show(supportFragmentManager, "MainUpdate")
            }
        })
    }

    override fun onResume() {
        super.onResume()
        Log.i("MainActivity","onResume")
        if(!GPSUtil.isOPen(getContext())){
            openGPS()
        }
    }

    override fun onSupportNavigateUp() = findNavController(R.id.fragment).navigateUp()

    private fun reStartAlarm() {
        val alarmData = PreferenceManager.getAlarmData(this)
        alarmData?.let {
            val tempData = it.split(" ")
            if(tempData.size != 2) return
            if(tempData[1].toLong() < System.currentTimeMillis()) return
            AlarmUtil.startAlarm(
                this,
                tempData[0].toInt(),
                tempData[1].toLong(),
                "MY_ALARM"
            )
        }
    }


    private fun openGPS() {
        AlertDialogFragment.MyBuilder(getContext())
            .setTitle("提示")
            .setMessage("请打开GPS以获取精确位置信息")
            .setPositiveButton("去打开") { dialog, which ->
                // 转到手机设置界面，用户设置GPS
                val intent = Intent(
                    Settings.ACTION_LOCATION_SOURCE_SETTINGS
                )
                startActivityForResult(intent, 0) // 设置完成后返回到原来的界面
            }
            .setCancelable(false)
            .create()
            .show(supportFragmentManager,"GPS")
    }

    fun wakeLock() {
        var powerManager = getSystemService(POWER_SERVICE) as PowerManager
        var wakeLock = powerManager.newWakeLock(
            PowerManager.PARTIAL_WAKE_LOCK,
            "cn.globalph.housekeeper:MyWakelockTag"
        )
        wakeLock.acquire()

    }

    fun isIgnoreBatteryOption(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                var intent = Intent();
                var packageName = activity.getPackageName();
                var pm = activity.getSystemService(Context.POWER_SERVICE) as PowerManager
                if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                    //               intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
                    intent.setAction(ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + packageName));
                    activity.startActivityForResult(intent, REQUEST_IGNORE_BATTERY_CODE)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    @AfterPermissionGranted(STORAGE_PERMISSION)
    private fun downLoadUpdate() {
        if (EasyPermissions.hasPermissions(this, *updatePermission)) {
            val intent = Intent(getContext(), UpdateService::class.java)
            intent.putExtra(UpdateService.UPDATE_URL, updateUrl)
            getContext().startService(intent)
            val downLoaderDialog = DownLoaderDialog()
            downLoaderDialog.show(supportFragmentManager, "download")
        } else {
            EasyPermissions.requestPermissions(
                this, getString(R.string.permission_update),
                STORAGE_PERMISSION, *updatePermission
            )
        }
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {

    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        locationObserver.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults,this)
    }
}
